package day05.Test1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

interface Speakable {
    void speak(String message);
}

abstract class Person implements Speakable {
    public abstract String toString();
}

class Teacher extends Person {
    public Teacher() {
    }

    public String positon;
    private int salary;

    public void speak(String message) {
        System.out.println("Speak: " + message);
    }

    @Override
    public String toString() {
        return "[Positon=" + positon + " salary= " + salary + "]";
    }

    public int getSalary() {
        return salary;
    }
}

public class Test {
    public static void main(String[] args) throws ClassNotFoundException,
            NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        // 0-通过反射创建 Teacher 的对象
        // 0-0 获取 Teacher 类的 Class 对象 clazz
        Class<?> clazz = Class.forName("day05.Test1.Teacher");

        // 0-1 获取 clazz 的 Constructor 对象 constructor
        Constructor<?> constructor = clazz.getConstructor();

        // 通过 constructor 对象创建 Teacher 对象 t
        Teacher t = (Teacher) constructor.newInstance();

        // 1-通过反射执行 t 对象的 Speak 方法
        t.speak("123456!");

        // 2-通过反射设置 t 对象的属性 position 的属性值为”Master”
        Field positionField = clazz.getField("positon");
        positionField.set(t, "Master");

        // 3 通过反射设置 t 对象私有属性 salary 的值为 7000
        Field salaryField = clazz.getDeclaredField("salary");
        salaryField.setAccessible(true);
        salaryField.setInt(t, 7000);

        System.out.println(t.toString());
    }
}